<!-- 自定义图片查看 -->
<template>
  <div class="CustomImage-root">
    <div class="loading-box" v-if="loading">
      <a-spin />
    </div>
    <template v-else>
      <template v-if="src">
        <img v-if="preview" :style="style" :src="src" @click="hanldeFullPreview" />
        <img v-else :style="style" :src="src" />
      </template>
      <template v-else>
        <span>暂无</span>
      </template>
    </template>
  </div>
</template>

<script>
import Vue from 'vue';
import CustomImagePreview from './CustomImagePreview';

const FullPreview = Vue.extend(CustomImagePreview);

export default {
  name: 'CustomImage',
  props: {
    src: {
      type: String,
    },
    width: {
      type: String,
    },
    height: {
      type: String,
    },
    preview: {
      type: Boolean,
      default: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    style() {
      const s = { 'object-fit': 'contain' };
      if (typeof this.width === 'number') {
        s.width = this.width + 'px';
      } else if (typeof this.width === 'string') {
        s.width = this.width;
      }
      if (typeof this.height === 'number') {
        s.height = this.height + 'px';
      } else if (typeof this.height === 'string') {
        s.height = this.height;
      }
      if (this.preview) {
        s.cursor = 'pointer';
      }
      return s;
    },
  },
  methods: {
    hanldeFullPreview() {
      if (!this.src) return;
      const fullPreview = new FullPreview({
        data: {
          src: this.src,
        },
      });
      fullPreview.vm = fullPreview.$mount();
      const body = document.getElementsByTagName('body')[0];
      body.appendChild(fullPreview.vm.$el);
    },
  },
};
</script>

<style lang="scss" scoped>
.CustomImage-root {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  img {
    width: 100%;
    height: 100%;
  }
  .loading-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.2);
  }
}
</style>
